module sobel(
	iclk			,
	idata			,
	idval			,
	irst_n		,
	ithreshold	,
	odval			,
	odata				
);

	input iclk;
	input irst_n;
	input [7:0] ithreshold;
	input idval;
	input [9:0] idata;
	output reg odval;
	output reg [9:0] odata;
	
	//将sobel 算子换算成有符号数   有符号数的二进制表示形式： 符号位+补码    计算结果最后要拆包
	parameter x1 = 8'hff, x2 = 8'h00, x3 = 8'h01;
	parameter x4 = 8'hfe, x5 = 8'h00, x6 = 8'h02;
	parameter x7 = 8'hff, x8 = 8'h00, x9 = 8'h01;


	parameter y1 = 8'h01, y2 = 8'h02, y3 = 8'h01;
	parameter y4 = 8'h00, y5 = 8'h00, y6 = 8'h00;
	parameter y7 = 8'hff, y8 = 8'hfe, y9 = 8'hff;
	
	wire  [7:0] Line0;
	wire  [7:0] Line1;
	wire  [7:0] Line2;
	wire  [17:0]  Mac_x0;
	wire  [17:0]  Mac_x1;
	wire  [17:0]  Mac_x2;
	wire  [17:0]  Mac_y0;
	wire  [17:0]  Mac_y1;
	wire  [17:0]  Mac_y2;
	wire  [19:0]  Pa_x;
	wire  [19:0]  Pa_y;
	wire  [15:0]  Abs_mag;

	LineBuffer LineBuffer_inst (
	  .clken(idval),
	  .clock(iclk),
	  .shiftin(idata[9:2]),
	  .taps0x(Line0),
	  .taps1x(Line1),
	  .taps2x(Line2)
	);

	// X
	MAC_3 x0_inst (
	  .aclr3(!irst_n),
	  .clock0(iclk),
	  .dataa_0(Line0),
	  .datab_0(x9),
	  .datab_1(x8),
	  .datab_2(x7),
	  .result(Mac_x0)
	);

	MAC_3 x1_inst (
	  .aclr3(!irst_n),
	  .clock0(iclk),
	  .dataa_0(Line1),
	  .datab_0(x6),
	  .datab_1(x5),
	  .datab_2(x4),
	  .result(Mac_x1)
	);

	MAC_3 x2_inst (
	  .aclr3(!irst_n),
	  .clock0(iclk),
	  .dataa_0(Line2),
	  .datab_0(x3),
	  .datab_1(x2),
	  .datab_2(x1),
	  .result(Mac_x2)
	);

	// Y
	MAC_3 y0_inst (
	  .aclr3(!irst_n),
	  .clock0(iclk),
	  .dataa_0(Line0),
	  .datab_0(y9),
	  .datab_1(y8),
	  .datab_2(y7),
	  .result(Mac_y0)
	);

	MAC_3 y1_inst (
	  .aclr3(!irst_n),
	  .clock0(iclk),
	  .dataa_0(Line1),
	  .datab_0(y6),
	  .datab_1(y5),
	  .datab_2(y4),
	  .result(Mac_y1)
	);

	MAC_3 y2_inst (
	  .aclr3(!irst_n),
	  .clock0(iclk),
	  .dataa_0(Line2),
	  .datab_0(y3),
	  .datab_1(y2),
	  .datab_2(y1),
	  .result(Mac_y2)
	);

	ADD pa0 (
	  .clock(iclk),
	  .data0x(Mac_x0),
	  .data1x(Mac_x1),
	  .data2x(Mac_x2),
	  .result(Pa_x)
	);

	ADD pa1 (
	  .clock(iclk),
	  .data0x(Mac_y0),
	  .data1x(Mac_y1),
	  .data2x(Mac_y2),
	  .result(Pa_y)
	);

	SQRT sqrt0 (
	  .clk(iclk),
	  .radical(Pa_x * Pa_x + Pa_y * Pa_y),
	  .q(Abs_mag)
	);

	always@(posedge iclk or negedge irst_n)
	if (!irst_n)
		odval <= 0;
	else 
		begin
			odval <= idval; //像素数据有效信号
			if (idval)
				odata<= (Abs_mag > ithreshold) ? 0 : 1023;
			else
				odata <= 0;
	  end

endmodule 